<template>
  <div class="control list_container flex both-100">
    <div class="content_container">
      <!-- 新增 -->
      <el-form ref="searchForm" :model="searchMap">
        <div class="search_wrapper flex-space-between el-form--inline" style="margin-top: 20px;">
          <div class="edit">
            <el-form-item class="flex">
              <el-button @click="handleAdd()" class="btn_primary el-icon-plus">新增</el-button>
            </el-form-item>
          </div>

        </div>
      </el-form>
      <div class="table_container">
        <!-- 表格 -->
        <el-table :data="dataList" v-loading="loading" stripe class="per_table" style="width: 100%" height="500">
          <el-table-column type="index" width="150" label="序号" align="center" />
          <el-table-column prop="emergencyCardName" label="应急卡名称" align="center"></el-table-column>
          <el-table-column prop="emergencyPlanName" label="所属预案" align="center"></el-table-column>
          <el-table-column prop="enableStatus" label="是否有效" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.enableStatus === '1'">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <div>
                <span type="text" class="tag_primary" size="small" @click="handleSelect(scope.row)">查看</span>
                <span type="text" class="marginl-10 tag_primary" size="small" @click="handleEdit(scope.row)">编辑</span>
                <span type="text" class="marginl-10 tag_warning" size="small" @click="handleDelete(scope.row)">删除</span>
                <span>
                  <el-dropdown @command="handleCommand" v-if="scope.row.attachment.length > 0">
                    <span class="el-dropdown-link">
                      <span type="text" class="marginl-10 tag_warning" size="small">下载附件</span>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="(item, index) in scope.row.attachment" :key="index" :command="item">{{
                        handleStr(item) }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <span class="el-dropdown-link" v-else>
                    <span type="text" class="marginl-10 tag_warning" size="small">暂无附件</span>
                  </span>
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize"
        @change="getList"></Pagination>
    </div>

    <!-- 弹窗 详情 -->
    <el-dialog class="m_dialog" :title="title" :visible.sync="dialogVisible" width="800" append-to-body
      :before-close="() => { dialogVisible = false }" :close-on-click-modal="false">
      <div class="content">
        <el-form ref="form" :model="formModel" :rules="formRules" size="small" label-width="80px"
          :disabled="title === '应急卡详情'">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="应急卡名称" label-width="120px" prop="emergencyCardName">
                <el-input v-model="formModel.emergencyCardName" placeholder="请输入应急卡名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属预案" label-width="120px" prop="emergencyPlanId">
                <el-select v-model="formModel.emergencyPlanId" placeholder="请输入所属预案" style="width: 100%;">
                  <el-option v-for="(item, index) in emergencyList" :label="item.emergencyPlanName"
                    :value="item.emergencyPlanId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否有效" label-width="120px" prop="enableStatus">
                <template>
                  <el-radio v-model="formModel.enableStatus" label="1">有效</el-radio>
                  <el-radio v-model="formModel.enableStatus" label="0">无效</el-radio>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件" label-width="120px">
                <uploadFile :disabled="title === '应急卡详情'" :value="formModel.attachment" :fileType="fileType"
                  @change="changeImg" @remove="removeImg"></uploadFile>
                <p style="color:red;">支持扩展名：.pdf .bmp .gif .jpg .jpeg .png</p>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" v-show="title === '应急卡详情'">
        <el-button @click="() => { dialogVisible = false }" class="btn_cancel">关 闭</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-show="title !== '应急卡详情'">
        <el-button @click="() => { dialogVisible = false }" class="btn_cancel">取 消</el-button>
        <el-button type="primary" @click="submitFrom()" class="btn_primary">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="dialogVisibleInfo" width="800" append-to-body>
      <custom-title title="详细信息" />
      <BaseDescriptions :descConfig="descConfig" :descConfigItem="descConfigItem" :descModel="formModel">
        <template #enableStatus>
          {{ formModel.enableStatus === '1' ? '有效' : '无效' }}
        </template>
        <template #attachment>
          <uploadFile :isUploadShow="false" :value="formModel.attachment"
            :deleteFlag="true" :fileType="fileType" @change="changeImg" @remove="removeImg" >
          </uploadFile>
        </template>
      </BaseDescriptions>
    </el-dialog>
  </div>
</template>
<script>
import { emergencyCardHandle, emergencyCardList, emergencyPlanList } from '../api/index'

import uploadFile from '@/components/UploadFiles2/index'
import BaseDescriptions from '@/components/PageContent/BaseDescriptions.vue';

import axios from 'axios';

export default {
  name: 'emergency',
  dicts: ['reserve_plan_type'],
  components: {
    uploadFile,
    BaseDescriptions,
  },
  props: {
    projectPointInfo: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      loading: true,
      total: 0,
      title: '应急卡详情',
      formType: 'basicInformation',
      dialogVisible: false,
      dialogVisibleInfo: false,
      searchMap: {
        pageNum: 1,
        pageSize: 10,
      },
      dataList: [],
      fileType: ['pdf', 'bmp', 'gif', 'jpg', 'jpeg', 'png'],
      // 提交表单数据
      formModel: {
        attachment: [],
      },
      emergencyList: [],
      reqType: 'post',
      formRules: {
        emergencyCardName: {
          required: true,
          message: "应急卡名称不能为空",
          trigger: "change",
        },
        emergencyPlanId: {
          required: true,
          message: "预案名称不能为空",
          trigger: "change",
        },
        enableStatus: {
          required: true,
          message: "请选择",
          trigger: "change",
        },
      },
      descConfig: {
        size: 'medium',
        column: '2',
      },
      descConfigItem: [
        {
          fieIdName: 'emergencyCardName',
          label: '应急卡名称',
          span: 2,
        },
        {
          fieIdName: 'emergencyPlanName',
          label: '所属预案',
          span: 2,
        },
        {
          fieIdName: 'enableStatus',
          label: '是否有效',
          span: 12,
          slotName: 'enableStatus',
        },
        {
          fieIdName: 'attachment',
          label: '附件',
          span: 12,
          slotName: 'attachment',
        },
      ],
    }
  },
  methods: {
    submitFrom() {
      this.formModel.projectPointId = this.projectPointInfo.projectPointId
      console.log(this.formModel)
      this.$refs.form.validate((valid) => {
        if (valid) {
          emergencyCardHandle(this.formModel, this.reqType).then(res => {
            if (200 === res.code) {
              this.$message({
                message: '操作成功',
                type: 'success',
              });
              this.dialogVisible = false
              this.formModel = {}
              this.getList()
            }
          });
        } else {
          return false;
        }
      });
    },
    //删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        emergencyCardHandle([row.emergencyCardId], 'delete').then(res => {
          if (200 === res.code) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //新增打开
    handleAdd() {
      this.title = "新增应急卡"
      this.reqType = 'post'
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.formModel = {}
      this.$set(this.formModel, 'attachment', [])
      this.dialogVisible = true;
    },
    //编辑
    handleEdit(row) {
      this.title = "编辑应急卡"
      this.formModel = row
      this.$set(this.formModel, 'attachment', row.attachment)
      this.reqType = 'put'
      this.dialogVisible = true;
    },
    //查看
    handleSelect(row) {
      this.title = "应急卡详情"
      this.reqType = 'select'
      this.formModel = row
      this.dialogVisibleInfo = true;
      // this.emergencyList.forEach(item => {
      //   if(item.emergencyPlanId === row.emergencyPlanId){
      // // this.formModel.emergencyPlanId = 

      //   }
      // })
    },
    //下载
    handleDownload(row) {
      console.log(row)
    },
    handleCommand(command) {
      console.log(command)
      const extension = command.match(/\.(\w+)$/)[1];
      if (extension === 'pdf') {
        this.downloadPdfBlob(this.$store.state.config.inFilePrefix + command, '附件')
      } else {
        this.downloadByBlob(this.$store.state.config.inFilePrefix + command, '附件')
      }
    },
    downloadPdfBlob(url, name) {
      console.log('22')
      axios({
        url: url,
        method: 'GET',
        responseType: 'blob'
      }).then(res => {
        let blob = new Blob([res.data], { type: 'application/pdf' })
        let url = window.URL.createObjectURL(blob)
        let a = document.createElement('a')
        a.href = url
        a.download = name
        a.click()
        a.remove()
        window.URL.revokeObjectURL(url)
      })
    },
    downloadByBlob(url, name) {
      console.log('11')
      let image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.src = url;
      image.onload = () => {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);
        canvas.toBlob(blob => {
          let url = URL.createObjectURL(blob);
          let a = document.createElement("a");
          a.download = name;
          a.href = url;
          a.click();
          a.remove();
          // 用完释放URL对象
          URL.revokeObjectURL(url);
        });
      };
    },
    handleStr(val) {
      console.log(val)
      const parts = val.split('/');
      return parts[parts.length - 1]
    },
    // 项目点图片修改
    changeImg(item) {
      if (!this.formModel.attachment) {
        this.formModel.attachment = []
      }
      this.formModel.attachment.push(item.url)
    },
    removeImg(item) {
      this.formModel.attachment.splice(this.formModel.attachment.indexOf(item.url), 1)
    },
    // 页面数据
    async getList() {
      const { code, rows, total } = await emergencyCardList(this.searchMap)
      if (code === 200) {
        this.loading = false
        this.dataList = rows
        this.total = total
      }
    },
    // 预案数据
    async getEmergencyList() {
      const { code, rows, total } = await emergencyPlanList(this.searchMap)
      if (code === 200) {
        this.loading = false
        this.emergencyList = rows
      }
    },
  },
  mounted() {
    this.searchMap.projectPointId = this.projectPointInfo.projectPointId
    this.getList()
    this.getEmergencyList()
    console.log(this.projectPointInfo, '111')
  },
}
</script>
<style lang="less">
.control {
  .el-table__cell {
    .cell {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
<style lang="less" scoped>
.list_container {
  flex-direction: column;
  background: url("@/assets/images/home/content.png") no-repeat;
  background-size: cover;

  .content_container {
    padding: 15px 20px;
    overflow-y: scroll;
  }

  .table_container {
    margin-bottom: 25px;
  }

  .pagination_container {
    display: flex;
    justify-content: space-between;
    height: 32px;
  }
}
</style>